package com.ukao.steward.ui.valetRunners.createOrder;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ukao.steward.R;
import com.ukao.steward.base.BaseFragment;
import com.ukao.steward.bean.StringBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.eventbus.ShoppEvent;
import com.ukao.steward.listener.MyTextWatcher;
import com.ukao.steward.retrofit.ApiCallback;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.DecimalUtil;
import com.ukao.steward.util.L;
import com.ukao.steward.util.T;
import com.ukao.steward.widget.StateImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link EasyOrederFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class EasyOrederFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.subtract_btn)
    StateImageView subtractBtn;
    @BindView(R.id.count)
    EditText count;
    @BindView(R.id.add_btn)
    StateImageView addBtn;
    @BindView(R.id.next_btn)
    Button nextBtn;
    Unbinder unbinder;
    @BindView(R.id.total_price)
    EditText totalPrice;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private String userId,takeAddressId,phone,name;
    private boolean isOrderdetailEnter;


    public static EasyOrederFragment newInstance(String takeAddressId, String userId,String  name ,String  phone) {
        EasyOrederFragment fragment = new EasyOrederFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, takeAddressId);
        args.putString(ARG_PARAM2, userId);
        args.putString(Constant.ARG_PARAM3, name);
        args.putString(Constant.ARG_PARAM4, phone);
        fragment.setArguments(args);
        return fragment;
    }

    public static EasyOrederFragment newInstance(String  order,boolean isOrderdetailEnter) {
        EasyOrederFragment fragment = new EasyOrederFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM2, order);
        args.putBoolean(Constant.ARG_PARAM5, isOrderdetailEnter);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            takeAddressId = getArguments().getString(ARG_PARAM1);
            userId= getArguments().getString(ARG_PARAM2);
            name = getArguments().getString(Constant.ARG_PARAM3);
            phone= getArguments().getString(Constant.ARG_PARAM4);
            isOrderdetailEnter= getArguments().getBoolean(Constant.ARG_PARAM5,false);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_easy_oreder, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    protected void initView() {
        if (isOrderdetailEnter){
            nextBtn.setText("確定");
        }
        title.setText("订单信息");
        setStatusBarTintColor(R.color.normal_blue);
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));

    }
    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(ShoppEvent event) {
        switch (event.getMessage()) {

            case FINISH:
                if (isAdded()){
                    finish();
                }

                break;



        }
    }
    @Override
    protected void initListener() {
        super.initListener();
        totalPrice.addTextChangedListener(mTextWatcher);
        totalPrice.setOnEditorActionListener(mOnEditorActionListener);

    }

    private TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            L.i("event=" + event + "actionId=" + actionId);
            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                    || actionId == EditorInfo.IME_ACTION_DONE||actionId == EditorInfo.IME_ACTION_NEXT) {
                nextJump();

            }

            return false;
        }
    };


    private TextWatcher mTextWatcher = new MyTextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            Constant.calculate(s.toString(), totalPrice);
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.add_btn, R.id.next_btn, R.id.subtract_btn,R.id.back_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case  R.id.back_btn:
                finish();
                break;


            case R.id.next_btn:
                nextJump();


                break;
            case R.id.subtract_btn:/*减去*/
                if (!CheckUtils.isEmpty(getText(count))) {
                    int clothingCount = Integer.valueOf(getText(count));
                    if (clothingCount > 0) {
                        clothingCount = clothingCount - 1;
                        String strclothingCount = String.valueOf(clothingCount);
                        count.setText(strclothingCount);
                        count.setSelection(strclothingCount.length());
                    }
                }


                break;

            case R.id.add_btn:/*加*/
                String strcount = getText(count);
                if (!CheckUtils.isEmpty(strcount)) {
                    int clothingCount1 = Integer.valueOf(strcount);
                    clothingCount1 = clothingCount1 + 1;
                    String strclothingCount1 = String.valueOf(clothingCount1);
                    count.setText(strclothingCount1);
                    count.setSelection(strclothingCount1.length());
                } else {
                    count.setText("1");
                    count.setSelection(1);
                }

        }
    }

    private void nextJump() {
        String   createCnt =getText(count);
        String payablePrice = getText(totalPrice);
        if (isOrderdetailEnter){
            createCnt= createCnt.isEmpty()? "0" :createCnt;
            payablePrice= payablePrice.isEmpty()? "0.00" :payablePrice;
            submitValuation(userId,createCnt,payablePrice);


        }else{
            start(CreateOrderFragment.newInstance( takeAddressId,  userId,  createCnt,
                    DecimalUtil.multiply(payablePrice,"1"),
                    phone,  name));
        }

    }
    /**
     提交计算
     */
    public void submitValuation(final String  orderId, final String  createCnt,  final String  payablePrice ) {
        showProgressDialog();
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("id",orderId);
        mHashMap.put("proCnt",createCnt);
        mHashMap.put("price", DecimalUtil.multiply(payablePrice));
        mHashMap.put("accessToken", SaveParams.getToken());
        addSubscription(apiStores().valuation(Constant.createParameter(mHashMap)),
                new ApiCallback<StringBean>() {
                    @Override
                    public void onSuccess(StringBean model) {

                        if (model.getHttpCode() == 200) {
                            Bundle  mBundle=new Bundle();
                            mBundle.putString(Constant.ARG_PARAM1,createCnt);
                            mBundle.putString(Constant.ARG_PARAM2,DecimalUtil.multiply(payablePrice,"1"));
                            setFragmentResult(RESULT_OK, mBundle);
                            finish();

                        }else{

                            T.show(model.getMsg());
                        }

                    }


                    @Override
                    public void onFinish() {

                       dismissProgressDialog();

                    }
                });

    }



}
